import json
def json_dump():
	mydict = {
		'name' : 'Amy',
		'age' : 20,
		'friends':['Alice','Rachel'],
		'cars':[
			{'brand':'BYD','max_speed':180},
			{'brand':'Audi','max_speed':280}
		]

	}

	# 方式一：dump - 将Python对象按照JSON格式序列化到文件中
	try:
		with open('data.json', 'w', encoding ='utf-8') as fs:
			json.dump(mydict,fs)
	except IOError as e:
		print(e)
	print('保存完成')


	# 方式二：dumps - 将Python对象处理成JSON格式的字符串，此时可以直接用write
	aa = json.dumps(mydict)
	print('方式二',type(aa))
	try:
		with open('data2.json', 'w', encoding ='utf-8') as fs:
			fs.write(aa)
	except IOError as e:
		print(e)
	print('2保存完成')
		


def json_load():
	try:
		with open('data.json', 'r', encoding ='utf-8') as fr:
			# load：将文件中的JSON数据反序列化成对象
			data = json.load(fr)
			print(data)
			print('反序列化load:',type(data))
	except IOError as e:
		print(e)

def josn_loads():
	json_str = '{"name": "骆昊", "age": 38, "title": "叫兽"}'
	# loads：将字符串中的内容反序列化成Python对象
	result = json.loads(json_str)
	print(type(result))
	print(result)

if __name__ == '__main__':
	json_dump()
	json_load()
	josn_loads()